<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	#set($prefix = "formData.")
	#set($prefix5 = "$.")
		<div id="page-wrapper">
            <div class="row">
            <div class="col-lg-12">
				<div class="panel panel-default">
                	<div class="panel-heading">
                        修改${entity.entityCN}
                    </div>
	                <div class="panel-body">
	                	<form role="form" id="${entity.module}${entity.entityName}UpdateForm" class="form-horizontal" 
							action="${pageContext.request.contextPath}/${entity.module}/${entity.entityNameLowerFirstChar}/update"
							method="post" enctype="multipart/form-data">
							#foreach($col in $entity.keys)
			                <div class="form-group">
			                    <label class="col-sm-2 control-label">${col.fieldCN}</label>
			                    <div class="col-sm-10">
			                    	<input class="form-control" name="${col.fieldName}" readonly value="${${prefix}${col.fieldName}}">
			                    </div>
			                </div>
			                #end
			                #foreach($col in $entity.columns)
			                <div class="form-group">
			                    <label class="col-sm-2 control-label">${col.fieldCN}</label>
			                    <div class="col-sm-10">
			                    	<input class="form-control" placeholder="请输入${col.fieldCN}" name="${col.fieldName}" value="${${prefix}${col.fieldName}}">
			                    </div>
			                </div>
			                #end
			                #foreach ($r in $entity.relationsM21)
			                #if($r.relatedRelation.relateWeakEntity())
			                <input type="hidden" name="${r.sourceFieldName}${r.target.firstKeyField.fieldNameUpperFirstChar}" value="${${prefix}${r.sourceFieldName}${r.target.firstKeyField.fieldNameUpperFirstChar}}">
			                #else
			                <div class="form-group">
								<label class="col-sm-2 control-label">${r.sourceFieldCN}</label>
								<div class="input-group">
									<input type="hidden" name="${r.sourceFieldName}${r.target.firstKeyField.fieldNameUpperFirstChar}" 
										value="${${prefix}${r.sourceFieldName}${r.target.firstKeyField.fieldNameUpperFirstChar}}">
		                            <input type="text" class="form-control" name="${r.sourceFieldName}${r.target.firstColumnField.fieldNameUpperFirstChar}" readonly 
		                            	value="${${prefix}${r.sourceFieldName}${r.target.firstColumnField.fieldNameUpperFirstChar}}">
		                            <span class="input-group-btn woSingleSelect" wo:url="${r.target.module}/${r.target.entityNameLowerFirstChar}/selector">
		                                <button class="btn btn-default" type="button"><i class="fa fa-search"></i>
		                                </button>
		                            </span>
	                            </div>
	                        </div>
			                #end
			                #end
			                #foreach ($r in $entity.relationsM2M)
			                <div class="form-group">
								<label class="col-sm-2 control-label">${r.sourceFieldCN}</label>
								<div class="input-group">
									<input type="hidden" name="${r.sourceFieldName}${r.target.firstKeyField.fieldNameUpperFirstChar}" 
										value="${${prefix}${r.sourceFieldName}${r.target.firstKeyField.fieldNameUpperFirstChar}}">
		                            <input type="text" class="form-control" name="${r.sourceFieldName}${r.target.firstColumnField.fieldNameUpperFirstChar}" readonly 
		                            	value="${${prefix}${r.sourceFieldName}${r.target.firstColumnField.fieldNameUpperFirstChar}}">
		                            <span class="input-group-btn" wo:url="${r.target.module}/${r.target.entityNameLowerFirstChar}/selector">
		                                <button class="btn btn-default" type="button"><i class="fa fa-search"></i>
		                                </button>
		                            </span>
	                            </div>
	                        </div>
			                #end
			                <div class="form-group">
			                <div class="col-sm-2"></div>
			                <div class="col-sm-10">
				                <button type="submit" class="btn btn-primary">提交</button>
				                <button type="reset" class="btn btn-default">重置</button>
				                <button type="button" class="btn btn-warning" onclick="location.href='${pageContext.request.contextPath}/'">返回</button>
			                </div>
			                </div>
			            </form>
	                </div>
                </div>
                </div>
                <!-- /.panel-body -->
            </div>
            #foreach ($r in $entity.relations12M)
            #if($r.relateWeakEntity())
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                    	<div class="panel-heading">
                        	${r.target.entityCN}
                    	</div>
                        <!-- /.panel-heading -->
                        <div class="panel-body">
                            <table width="100%" class="table table-striped table-bordered table-hover" id="${entity.module}${entity.entityName}${r.sourceFieldName}Table">
                                <thead>
                                    <tr>
                                        <th>${r.target.firstKeyField.fieldCN}</th>
                                        #foreach($col in $r.target.columns)
                                        <th>${col.fieldCN}</th>
                                        #end
                                        #foreach ($rM21 in $r.target.relationsM21)
                                        <th>${rM21.sourceFieldCN}</th>
                                        #end
                                        <th>操作</th>
                                    </tr>
                                </thead>
                            </table>
                            <!-- /.table-responsive -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
            #end
            #end
            <script type="text/javascript">
	   	    $(document).ready(function () {
	   	  		// 设置各字段的验证规则
	   	    	var fields = {};
	   	    	#foreach($col in $entity.keys)
	   	    	if (!fields['${col.fieldName}']) {
	   	    		fields['${col.fieldName}'] = {validators:{}};
	   	    	}
	   	    	fields['${col.fieldName}'].validators['notEmpty'] = {
	   	    		message: '${col.fieldCN}不能为空'
	   	    	};
	   	    	#end
	   	    	#foreach($col in $entity.columns)
	   	    	if (!fields['${col.fieldName}']) {
	   	    		fields['${col.fieldName}'] = {validators:{}};
	   	    	}
	   	    	#if (${col.isRequired()})
	   	    	fields['${col.fieldName}'].validators['notEmpty'] = {
	   	    		message: '${col.fieldCN}不能为空'
	   	    	};
	   	    	#end
	   	    	#end
	   	  		// 将验证规则应用到表单的字段中
	   			$('#${entity.module}${entity.entityName}UpdateForm').bootstrapValidator({
		            // 默认错误消息
	   				message: '输入值不合法',
	   				// 设置验证成功或者失败的图标
		            feedbackIcons: {
		                valid: 'glyphicon glyphicon-ok',
		                invalid: 'glyphicon glyphicon-remove',
		                validating: 'glyphicon glyphicon-refresh'
		            },
		            // 设置不同字段的验证规则和错误信息
		            fields: fields
		        });
	   	    	
	   	  		// 关联对象选择器按钮点击事件
	   	    	$('#${entity.module}${entity.entityName}UpdateForm .input-group-btn').click (function () {
					var nameField = $(this).prev().attr ('name');
					var idField = $(this).prev().prev().attr ('name');
					$('#${entity.module}${entity.entityName}Dialog').remove();
	            	$('body').append ('<div class="modal fade" id="${entity.module}${entity.entityName}Dialog" tabindex="-1" role="dialog" aria-labelledby="${entity.module}${entity.entityName}SelectorModalLabel"></div>');
	            	// 显示对话框
	            	$('#${entity.module}${entity.entityName}Dialog').load ('${pageContext.request.contextPath}/' + $(this).attr('wo:url'), {
	            		formId : '${entity.module}${entity.entityName}UpdateForm',
	            		idField : idField,
	            		nameField : nameField,
	            		singleSelect : $(this).hasClass('woSingleSelect')
	            	},function () {
	            		$('#${entity.module}${entity.entityName}Dialog').modal ('show');
	            	});
				});
	   	  		
	   	    	#foreach ($r in $entity.relations12M)
	   	    	#if($r.relateWeakEntity())
	   	    	// ${r.target.entityCN}列表
	   	    	var ${r.sourceFieldName}TableId = '${entity.module}${entity.entityName}${r.sourceFieldName}Table';
            	var cols = [
            		{ "data": "${r.target.firstKeyField.fieldName}" , "orderable" : ${r.target.firstKeyField.isOrderable()}},
                	#foreach($col in $r.target.columns)
                	{ "data": "${col.fieldName}" , "orderable" : ${col.isOrderable()}},
                	#end
                	#foreach ($rM21 in $r.target.relationsM21)
                	{ "data": "${rM21.sourceFieldName}${rM21.target.firstColumnField.fieldNameUpperFirstChar}" , "orderable" : false},
                	#end
                    // 下面在"操作"列中添加了修改和删除按钮
                    { "data": null , "orderable" : false, "defaultContent": "<a class='btn btn-primary btn-xs' name='update'>修改</a> <a class='btn btn-primary btn-warning btn-xs' name='delete'>删除</a>"}
                ];
            	var orderIndex = 0;
            	for (var i = 0; i < cols.length; i ++) {
            		if (cols[i].orderable == true) {
            			orderIndex = i;
            		}
            	}
            	// 初始化列表，并触发后台的json数据获取
                var ${r.sourceFieldName}Table = $('#' + ${r.sourceFieldName}TableId).DataTable({
                	"processing": true, // 显示处理进度
                    "serverSide": true, // 从服务端获取数据
                    "rowId" : 'id',// 设置主键字段名称
                    "ajax": {
                        "url": "${pageContext.request.contextPath}/${r.target.module}/${r.target.entityNameLowerFirstChar}/list?${r.mappedBy}Id=" + $('#${entity.module}${entity.entityName}UpdateForm input[name=${entity.firstKeyField.fieldName}]').val(), // 请求列表数据的url
                        "type": "GET" // http方法
                    },
                    "order": [ [ orderIndex, "${r.target.orderableField.order}" ] ] , // 排序
                    "columns": cols
                });
                // 设置列表中按钮的事件
                $('#' + ${r.sourceFieldName}TableId + ' tbody').on( 'click', 'a', function () {
                	// this表示a标签对应dom，$(this)将其转为jQuery对象，获取按钮所在行的json对象:${r.target.entityName}Dto
                    var data = ${r.sourceFieldName}Table.row( $(this).parents('tr') ).data();
                	// 调用修改方法
                	if ($(this).attr('name') == 'update') {
                		update${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar}(data.${entity.firstKeyField.fieldName});
                	}
                	// 调用删除方法
					if ($(this).attr('name') == 'delete') {
						delete${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar} (data.${entity.firstKeyField.fieldName});
                	}
                } );
             	// 设置列表多选
                $('#' + ${r.sourceFieldName}TableId + ' tbody').on( 'click', 'tr', function () {
                	// 如果有info样式则删除，没有则添加
                	$(this).toggleClass('info');
                } );
             	
                // 添加工具栏按钮，找到设置分页的div，并添加创建和批量删除按钮的a标签
                $('#' + ${r.sourceFieldName}TableId + '_length').append (" <a class='btn btn-primary btn-sm' onclick='create${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar}();'>创建</a> <a class='btn btn-primary btn-warning btn-sm' onclick='delete${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar}s();'>批量删除</a>");
	   	    	#end
	   	    	#end
		    });
	   	    
	   	 	#foreach ($r in $entity.relations12M)
	    	#if($r.relateWeakEntity())
	   	 	function create${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar} () {
	         	location.href = "${pageContext.request.contextPath}/${r.target.module}/${r.target.entityNameLowerFirstChar}/create?${r.mappedBy}Id=" + $('#${entity.module}${entity.entityName}UpdateForm input[name=${entity.firstKeyField.fieldName}]').val();
	        }
	         
	        function update${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar} (id) {
	         	location.href = "${pageContext.request.contextPath}/${r.target.module}/${r.target.entityNameLowerFirstChar}/update?id=" + id;
	        }
	         
	        function delete${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar} (id) {
	         	if (!confirm ('确定要删除选定的${r.target.entityCN}吗？')) {
	         		return;
	         	}
	         	${prefix5}post ('${pageContext.request.contextPath}/${r.target.module}/${r.target.entityNameLowerFirstChar}/delete', {id : id}, function (result) {
		    		if (result.success) {
		    			var tableId = '${entity.module}${entity.entityName}${r.sourceFieldName}Table';
				    	var table = $('#' + tableId).DataTable();
				    	// 删除选中的行
		    			table.rows('.info').remove().draw(false);
		    		} 
		    		alert (result.message);
			    });
	        }
	         
	        function delete${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar}s () {
	         	// 获取DataTable
		    	var tableId = '${entity.module}${entity.entityName}${r.sourceFieldName}Table';
		    	var table = $('#' + tableId).DataTable();
		    	// 查找样式为info的行，包含所有${r.target.entityName}Dto属性
		    	var rows = table.rows('.info').data();
		    	// 判断${r.target.entityCN}是否有选择
		    	if (rows.length == 0) {
		    		alert ('请选择至少一个${r.target.entityCN}！');
		    		return;
		    	}
		    	// 让${r.target.entityCN}确认删除
		    	if (!confirm ('是否删除选中的${r.target.entityCN}？')) {
		    		return;
		    	}
		    	// 拼接id字符串，多个id逗号隔开
		    	var ids = '';
		    	for (var i = 0; i < rows.length; i ++) {
		    		if (ids != '') {
		    			ids += ',';
		    		}
		    		ids += rows[i].id;
		    	}
		    	// 发送ajax请求，如果成功刷新本页面，否则提示${r.target.entityCN}操作失败
		    	delete${entity.moduleUpperFirstChar}${entity.entityName}${r.sourceFieldNameUpperFirstChar}(ids);
		    }
	        #end
   	    	#end
   			</script>
		</div>